package com.zy

import java.util

import scala.collection.{SortedMap, mutable}

/**
 * @description: 第四章
 * @author: zhaoyi
 * @create: 2020-04-23 21:06
 **/
object Chapter4 {

  def main(args: Array[String]): Unit = {

    val map: Map[String, Any] = Map("a" -> 1, "b" -> "hello")
    println(map.mkString(","))

    //可变map
    val map2 = scala.collection.mutable.Map("a" -> 1, "b" -> 2)
    //相当于put
    map2("c") = 3
    map2.+=("d" -> 4)
    map2 -= "a"
    map2.-=("e")
    map2.put("f", 5)


    println(map2.mkString(","))

    //不存在会抛异常 Exception ... NoSuchElementException: key not found: a
    //println(map2("a"))

    //get方法会返回Option不会异常
    println(map2.get("a"))
    println(map2.getOrElse("a", 0))

    for ((k, v) <- map2) {
      print(s"[key: $k, value: $v] ")
    }
    map2.keySet.foreach(print)
    map2.values.foreach(print)

    //根据Key排序
    val sortMap = SortedMap("c"->3,"a"->1,"b"->2)
    println(sortMap.mkString(","))

    //插入顺序访问
    val linkMap = mutable.LinkedHashMap("c"->3,"b"->1,"a"->2)
    println(linkMap.mkString(","))

    //与java相互操作
    //java方法获取到java的map可以引入下面会转换城scala的map,便于使用scalaMap的API
    import scala.collection.JavaConversions.mapAsScalaMap
    val hashMap = new util.HashMap[String,Int]()
    //import  mapAsScalaMap 此时可以使用scalaMap的API
    hashMap("c") = 3


    //元祖
    val (name,age) = ("张三",18)
    println(name)
    println(age)
    println(Array((name,age)).toMap.getOrElse("张三",18))






  }

}
